#include "loginwindow.h"
#include "ui_loginwindow.h"
#include "registerwindow.h"

LoginWindow::LoginWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginWindow)
{
    ui->setupUi(this);
    setWindowTitle("登录");
//    QTcpSocket* socket = getsocket();
    SocketManager::instance()->connectToServer();
    connect(SocketManager::instance()->getsocket(),&QTcpSocket::connected,this,&LoginWindow::handleconnected);
    //connect(socket,&QTcpSocket::readyRead,this,&LoginWindow::handleTORead);
    connect(SocketManager::instance(), &SocketManager::loginResponse,
            this, &LoginWindow::handleLoginResponse);
}

void LoginWindow::on_login_clicked()
{
    QString username = ui->username->text();
    QString password = ui->password->text();

    if (username.isEmpty() || password.isEmpty())
    {
        ui->info->setStyleSheet("color:red");
        ui->info->setText("用户名或者密码为空!");
        return;
    }


    QTcpSocket* socket = SocketManager::instance()->getsocket();

    if (socket->state() == QAbstractSocket::UnconnectedState)
    {
        socket->connectToHost("127.0.0.1", 8081);
        ui->info->setText("正在连接服务器...");
        // 连接成功后会调用 handleconnected() 自动发送
    }
    else if (socket->state() == QAbstractSocket::ConnectedState)
    {
        QJsonObject json;
        json["MessageType"] = static_cast<int>(Protocol::MessageType::Msg_Login);
        json["username"] = username;
        json["password"] = password;

        QJsonDocument doc(json);
        QByteArray data = doc.toJson(QJsonDocument::Compact);

        data.append('\n');
        SocketManager::instance()->getsocket()->write(data);
    }
    else
    {
        ui->info->setText("连接服务器失败，请稍后重试");
    }
//    QString username = ui->login->text();
//    QString password = ui->password->text();
//    if(username.isEmpty()||password.isEmpty())
//    {
//        ui->info->setStyleSheet("color:red");
//        ui->info->setText("用户名或者密码为空!");
//    }
}


void LoginWindow::handleconnected()
{
      ui->info->setStyleSheet("color:green");
      ui->info->setText("连接服务器成功");
//    QJsonObject json;
//    json["MessageType"] = static_cast<int>(Protocol::MessageType::Msg_Login);
//    json["username"] = pendingUsername;
//    json["password"] = pendingPassword;

//    QJsonDocument doc(json);
//    QByteArray data = doc.toJson(QJsonDocument::Compact);

//    getsocket()->write(data);
}

//void LoginWindow::handleTORead()
//{
//    QByteArray data = getsocket()->readAll();

//    QJsonParseError error;
//    QJsonDocument doc = QJsonDocument::fromJson(data,&error);

//    if(error.error!=QJsonParseError::NoError)
//    {
//        ui->info->setStyleSheet("color:red");
//        ui->info->setText("Json串解析失败"+error.errorString());
//        return ;
//    }

//    if(!doc.isObject())
//    {
//        ui->info->setStyleSheet("color:red");
//        ui->info->setText("服务器返回的不是Json对象");
//        return ;
//    }

//    QJsonObject retjson = doc.object();
//    //解析json串内容
//    int type = retjson["MessageType"].toInt();
//    bool issuccess = retjson["success"].toBool();
//    QString username = retjson["username"].toString();
//    QString message = retjson["message"].toString();
//    switch (type)
//    {
//        case (int)(Protocol::ResponseType::Res_Login):
//                {
//                    if(issuccess)
//                    {
//                        ui->info->setStyleSheet("color:green");
//                        ui->info->setText(message);
//                        //跳转进聊天界面chatwindow
//                    }
//                    else
//                    {
//                        ui->info->setStyleSheet("color:red");
//                        ui->info->setText(message);
//                    }
//                }
//            break;
//        case (int)(Protocol::ResponseType::Res_Registe):
//                {

//                }
//            break;
//        case (int)(Protocol::ResponseType::Res_Chat):
//                {

//                }
//            break;
//        case (int)(Protocol::ResponseType::Res_ServerBroadcast):
//                {

//                }
//            break;
//        default:
//            break;
//    }

//}

void LoginWindow::handleLoginResponse(QJsonObject obj)
{
//      QJsonParseError error;
//      QJsonDocument doc = QJsonDocument::fromJson(data,&error);

//      if(error.error!=QJsonParseError::NoError)
//      {
//          ui->info->setStyleSheet("color:red");
//          ui->info->setText("Json串解析失败"+error.errorString());
//          return ;
//      }

//      if(!doc.isObject())
//      {
//          ui->info->setStyleSheet("color:red");
//          ui->info->setText("服务器返回的不是Json对象");
//          return ;
//      }

      QJsonObject retjson = obj;
      //解析json串内容

      bool issuccess = retjson["success"].toBool();
      QString username = retjson["username"].toString();
      QString message = retjson["message"].toString();

      if(issuccess)
      {
          ui->info->setStyleSheet("color:green");
          ui->info->setText(message);
          //跳转进聊天界面chatwindow
      }
      else
      {
          ui->info->setStyleSheet("color:red");
          ui->info->setText(message);
      }
}

//QTcpSocket *LoginWindow::getsocket()
//{
//    return SocketManager::getTcpsocket();
//}



void LoginWindow::on_Register_clicked()
{
    if(!reg)
    {
        reg = new RegisterWindow(this);
    }
    this->hide();
    reg->show();
}


LoginWindow::~LoginWindow()
{
    delete ui;
}
